<include file="Public/header1" title="文稿编辑" />
<link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<div class="main">
    <div class="wrap">
        <form id="articleForm" method="post">
            <!-- <input type="hidden" name="indexpic" id="indexpic" value="" /> -->
            <input type="hidden" name="aid" id="aid" value="{$Think.get.id}" />
            <div class="sidebar">
                <div class="cover">
                    <!--<div class="title">封面<span id="filePicker">选择图片</span></div>-->
                    <div class="cover-pic">
                        <?php if($article['indexpic']) { ?>
                        <img width="100%" src="{:C('UPLOAD_HOST')}{$article['indexpic']}" alt="" id="showpic">
                        <?php } else { ?>
                        <img width="100%" src="http://jianwei.appwuhan.net/Public/images/defaultpic.gif" alt="" id="showpic">
                        <?php } ?>
                    </div>
                </div>
                <div class="info">
                    <div class="title">发稿人</div>
                    <div class="divider"></div>
                    <div class="info-author">
                        <label for="author">作者：</label>
                        <span id="author">{$article.realname}</span>
                    </div>
                    <div class="divider"></div>
                    <div class="info-connect">
                        <label for="author">联合记者：</label>
                        <ul>
                            <?php foreach($article['authorlist'] as $val) { ?>
                            <li><?php echo $val; ?></li>
                            <?php } ?>
                            <!--<li>+</li>-->
                        </ul>
                        <div class="clr"></div>
                    </div>
                    <div class="divider"></div>
                </div>
                <div class="dest">
                    <div class="title">发送至</div>
                    <div class="divider"></div>
                    <ul class="dest-items">
                        <li class="items">
                            <input id="d1" type="checkbox" class="dest-check" checked readonly>
                            <label for="d1"><i></i>掌上武汉</label>
                        </li>
                        <li class="items disable">
                            <input id="d2" type="checkbox" class="dest-check" disabled>
                            <label for="d2"><i></i>黄鹤云</label>
                        </li>
                        <li class="items disable">
                            <input id="d3" type="checkbox" class="dest-check" disabled>
                            <label for="d3"><i></i>微信公众号</label>
                        </li>
                        <li class="items disable">
                            <input id="d4" type="checkbox" class="dest-check" disabled>
                            <label for="d4"><i></i>新浪微博</label>
                        </li>
                    </ul>
                    <div class="clr"></div>
                    <div class="divider"></div>
                    <a href="" class="origin">&copy;申明原创</a>
                </div>
            </div>
            <div class="content">
                <div class="nav">
                    <ul class="nav-pills">
                        <li><a href="/Home">首页</a></li>
                        <li><a href="/Home/Article/index">内容生产</a></li>
                        <li><a href="#">修改文稿</a></li>
                    </ul>
                </div>
                <div class="editor">
                    <input type="text" id="papertitle" class="title" name="title" value="{$article['title']}" style="display: block;">
                    <textarea id="paperedit" name="content" class="editor-content">{$article['content']|nl2br=###}</textarea>
                </div>
            </div>
            <div class="pic-list pics" :class="{open: show}">
                <div class="handle" v-if="show" v-on:click="hideimage()">收起图片</div>
                <div class="handle" v-else v-on:click="showimage()">展开图片</div>
                <ul class="imagelist">
                    <li class="items" v-for="item of images" v-on:click.stop.prevent="addImage(item)" style="position:relative;">
                        <img v-if="item.type=='image'" :src="item.path" :data-type="item.type"  alt="">
                        <!--<img v-if="item.type=='video'" :src="item.path" :data-type="item.type"  alt="">-->
                        <!--<img v-if="item.type=='audio'" src="__PUBLIC__/img/default-audio.jpg" :data-type="item.type"  alt="">-->
                        <div style="position:absolute;width:100%; heigth:36px; line-height: 36px; background: #fff;z-indent:2;left:0;top:0;" v-if="item.type=='image'">图片</div>
                        <!--<div style="position:absolute;width:100%; heigth:36px; line-height: 36px; background: #fff; z-indent:2;left:0;top:0;" v-else-if="item.type=='video'" :data-file="item.fullpath" onclick="showVideo(event)">视频预览</div>-->
                        <!--<div style="position:absolute;width:100%; heigth:36px; line-height: 36px; background: #fff;z-indent:2;left:0;top:0;" v-if="item.type=='audio'" :data-file="item.fullpath" onclick="showVideo(event)">音频试听</div>-->
                        <!--<div class="cls" v-on:click.stop.prevent="deleteImg(item)"></div>-->
                    </li>
                </ul>
            </div>

        <div class="pic-list video-list" :class="{open: show}" style="margin-top: 40px;">
            <div class="handle" v-if="show" v-on:click="hideimage()">收起附件</div>
            <div class="handle" v-else v-on:click="showimage()">展开附件</div>
            <ul class="imagelist">
                <li class="items" v-for="item of images" style="position:relative;">
                    <img v-if="item.type=='video'" :src="item.path" :data-type="item.type"  alt="">
                    <img v-if="item.type=='audio'" src="__PUBLIC__/img/default-audio.jpg" :data-type="item.type"  alt="">
                    <div class="itemwrap">
                        <div class="bg"></div>
                        <ul>
                            <li class="itemwrap-btn" v-if="item.type=='video'" :data-file="item.fullpath" onclick="showVideo(event)"><i class="fa fa-play-circle-o" aria-hidden="true"></i>&nbsp;预览</li>
                            <li class="itemwrap-btn" v-else="item.type=='audio'" :data-file="item.fullpath" onclick="showVideo(event)"><i class="fa fa-music" aria-hidden="true"></i>&nbsp;试听</li>
                            <li class="itemwrap-btn" v-on:click.stop.prevent="addImage(item)"><i class="fa fa-paperclip" aria-hidden="true"></i>&nbsp;插入</li>
                        </ul>
                    </div>

                    <!--<div class="cls" v-on:click.stop.prevent="deleteImg(item)"></div>-->
                </li>
            </ul>
        </div>
        </form>
    </div>

    <div class="footer">
        <div class="footer-wrap">
            <div class="pull-right">
                <button type="button" class="btn btn-primary submit">保存</button>
                <!--<a href="" class="btn btn-default">保存草稿</a>-->
                <a href="javascript:;" class="btn btn-default cancel" onclick="window.location.href = '{:U(\'index\')}'">取消</a>
            </div>
        </div>
    </div>
</div>
<!-- 24小时rtmp -->
<div class="modal fade bs-example-modal-sm" tabindex="-1" id="videobox" role="dialog" aria-labelledby="videobox"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" id="videodiv">
            <!--<video id="video" width="500" height="375" autoplay="autoplay" autobuffer="true" src=""></video>-->
            <div class="video-b">
                <video id="video_1" class="video-js vjs-default-skin" controls preload="none" width="598" height="464" data-setup="{}">
                    <source id="video" src="" type='video/mp4' />
                </video>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>

    </div>
</div>


<div class="modal fade" id="uploadVideo" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">上传音视频</h4>
            </div>
            <div class="modal-body">
                <div id="uploader-demo">
                    <!--用来存放item-->
                    <div class="btns">
                        <div id="picker">选择文件</div>
                        <!--<button id="ctlBtn" class="btn btn-default">开始上传</button>-->
                    </div>
                    <div id="thelist" class="uploader-list" style="display: none;"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button id="ctlBtn" type="button" class="btn btn-primary">开始上传</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>



<script src="__PUBLIC__/ckeditor/ckeditor.js"></script>
<link href="http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="http://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<!-- Chang URLs to wherever Video.js files will be hosted -->
<link href="__PUBLIC__/video-js/video-js.css" rel="stylesheet" type="text/css">
<!-- video.js must be in the <head> for older IEs to work. -->
<script src="__PUBLIC__/video-js/video.js"></script>

<script>
    var myPlayer;
    function showVideo(evt) {
        var url = $(evt.target).data('file');
        if(!/http/.test(url))
            url = '{:C("QINIU_RESOURCE_HOST")}' + url;
        console.log(url);
        videojs.options.flash.swf = "__PUBLIC__/video-js/video-js.swf";

        $("#videobox #video").attr('src', url);
        myPlayer =  videojs("video_1");  //初始化视频
        myPlayer.src(url);  //重置video的src
        myPlayer.load(url);  //使video重新加载

        $("#videobox").modal('show');
        evt.stopPropagation();
    }

    $('#videobox').on('hidden.bs.modal', function () {
        myPlayer.pause();
    })

    // 右侧表单
    var imgslist;
    // 编辑区域
    var contentEdit,titleEdit;
    // 页面缓存数据
    var paperData = {title:"",content:""};
    // ckeditor 设置
    var CKEDITOR_BASEPATH = '__PUBLIC__/ckeditor/';
    CKEDITOR.disableAutoInline = true;

    $(function () {

        $('.submit').click(function () {
            for(var instanceName in CKEDITOR.instances)
            {
                CKEDITOR.instances[instanceName].updateElement();
            }

            $('form').submit();
        });

//        titleEdit = CKEDITOR.inline( 'papertitle' );

        contentEdit = CKEDITOR.replace('paperedit',{
            extraPlugins:'confighelper',
        });

        contentEdit.on("instanceReady", function(event)
        {
            //put your code here
            //
            $("#cke_paperedit").find(".cke_top").append('<span id="imgPicker"><div class="webuploader-pick"></div></span><span id="filePicker"><div class="webuploader-pick"> </div></span><span id="uploadBtn" data-toggle="modal" data-target="#uploadVideo"><div class="webuploader-pick"> </div> </span>');
            $("#imgPicker").click(function(){
                if(!imgslist.show){
                    imgslist.show = true;
                    videolist.show = false;
                }
            })
            $("#filePicker").click(function(){
                if(!videolist.show){
                    imgslist.show = false;
                    videolist.show = true;
                }
            })

            $(".cke_button__image").closest(".cke_toolgroup").remove();
            reshow();

            $("#videobg, #audiobg",$('.cke_contents iframe').get(0).contentDocument).click(function(){
                videolist.show = true;
                imgslist.show = false;
            });

            $("img[data-type='image']",$('.cke_contents iframe').get(0).contentDocument).click(function(){
                videolist.show = false;
                imgslist.show = true;
            });
        });

        imgslist = new Vue({
            el: '.pic-list',
            data: {
                show: false,
                images: [
                ]
            },
            methods: {
                showimage: function () {
                    videolist.show = false;
                    this.show = true;
                },
                hideimage: function () {
                    this.show = false;
                },
                deleteImg: function (val) {
                    var index = this.images.indexOf(val);
                    this.images.splice(index,1);
                },
                addImage:function (val) {
//                    var tmp = contentEdit.getData();

                    if(val.type == 'video') {

//                        var newObj = '<object type="application/x-shockwave-flash" data="http://player.hoge.cn/player.swf" width="500" height="405">'
//                                + '<param name="movie" value=""><param name="allowscriptaccess" value="always">'
//                                + '<param name="allowFullScreen" value="true">'
//                                + '<param name="wmode" value="transparent">'
//                                + '<param name="flashvars" value="video=' + val.id +'&sideBarType=1&autoPlay=true&extendParam=132305&colid=135&config=104vod.xml"></object>';

                        var newObj = '<img data-videoid="' + val.id +'" src="' + val.path +'"/>';

                        console.log(newObj);
                    } else if(val.type == 'audio') {
                        var newObj = '<img data-videoid="' + val.id +'" src="__PUBLIC__/img/default-audio.jpg"/>';
                    } else {
                        var newObj = '<img width="100%" src="'+val.fullpath+'" id="' + val.id +'" data-type="' + val.type + '">';
                    }

                    InsertHtml(contentEdit,newObj);
//                    tmp += newImg;
//                    contentEdit.setData(tmp);
                }
            }
        })

        videolist = new Vue({
            el: '.video-list',
            data: {
                show: false,
                images: [
                ]
            },
            methods: {
                showimage: function () {
                    imgslist.show = false;
                    this.show = true;
                },
                hideimage: function () {
                    this.show = false;
                },
                deleteImg: function (val) {
                    var index = this.images.indexOf(val);
                    this.images.splice(index,1);
                },
                addImage:function (val) {
//                    var tmp = contentEdit.getData();
                    if(val.type == 'video') {
                        var newObj = '<p id="videobg"><img data-videoid="' + val.id +'" src="__PUBLIC__/img/playerpic.png" style="background:#000 url(' + val.path +') no-repeat center center;background-size:contain"/></p>';
                    } else if(val.type == 'audio') {
                        var newObj = '<p id="audiobg"><img data-videoid="' + val.id +'" src="__PUBLIC__/img/audiobg.png" /></p>';
                    }
                    InsertHtml(contentEdit,newObj);
/*                    $(".cke_contents iframe").contents().find("#videobg,#audiobg").click(function(){
                        videolist.show = true;
                        imgslist.show = false;
                    })*/

//                    tmp += newImg;
//                    contentEdit.setData(tmp);
                }
            }
        })
    })




    function autosave(){
        var title = titleEdit.getData();
        var content = contentEdit.getData();
        var period = 1 * 1 * 1000; // min- sec - mm
        setInterval(function () {
            title = titleEdit.getData();
            content = contentEdit.getData();
            localStorage.setItem("paperData[edit]",JSON.stringify({title:title,content:content}));
        },period);
    }

    function reshow() {
        //当cookies不为空
        if(localStorage.getItem("paperData[edit]")!=null || paperData.title !='' || paperData.content !=''){


            //加载cookies
            if(confirm("是否加载先前编辑的内容？")){
                paperData = JSON.parse(localStorage.getItem("paperData[edit]"));
                /*使用页面cookies*/
                titleEdit.setData(paperData.title);
                contentEdit.setData(paperData.content);
            }
        }
    }

    function InsertHtml(editor, value) {
        // Check the active editing mode.
        if (editor.mode == 'wysiwyg') {
            editor.insertHtml(value);
        } else {
            editor.setMode('wysiwyg', function() {
                editor.insertHtml(value);
                editor.setMode('source');
            });
        }
    }

//    $.get('{:U("getImageListByAid")}?id={$Think.get.id}', function(data) {
//        var data = $.parseJSON(data);
//        if(data.status == 1) {
//            for(var i in data.data) {
//                if(data.data[i]['type'] == 'image') {
//                    var newobj = {fullpath: '{:C("UPLOAD_HOST")}' + data.data[i]['filepath'] + data.data[i]['filename'],id:data.data[i]['attachid'],'path':'{:C("UPLOAD_HOST")}' + data.data[i]['thumb'],'type':data.data[i]['type'],'id ':data.data[i]['id'],'type':data.data[i]['type']};
//                    imgslist.images.push(newobj);
//                } else {
//                    if(/http/.test(data.data[i]['filepath'])) {
//                        var newobj = {fullpath: '{:C("UPLOAD_HOST")}' + data.data[i]['filepath'] + data.data[i]['filename'],id:data.data[i]['attachid'],'path':data.data[i]['thumb'],'type':data.data[i]['type'],'id ':data.data[i]['id'],'type':data.data[i]['type']};
//                    } else {
//                        var newobj = {fullpath: '{:C("UPLOAD_HOST")}' + data.data[i]['filepath'] + data.data[i]['filename'],id:data.data[i]['attachid'],'path':'{:C("UPLOAD_HOST")}' + data.data[i]['thumb'],'type':data.data[i]['type'],'id ':data.data[i]['id'],'type':data.data[i]['type']};
//                    }
//
//                    videolist.images.push(newobj);
//                }
//
//            }
//        }
//
//    })


    $.get('{:U("getImageListByAid")}?id={$Think.get.id}', function(data) {
        var data = $.parseJSON(data);
        if(data.status == 1) {
            for(var i in data.data) {
                var client_attach_id = data.data[i]['client_attach_id'];
                var host = '{:C("UPLOAD_HOST")}';
                if(client_attach_id) {
                    host = '{:C("QINIU_RESOURCE_HOST")}';
                }
                var newobj = {fullpath: host + data.data[i]['filepath'] + data.data[i]['filename'],id:data.data[i]['attachid'],'path':host + data.data[i]['thumb'],'type':data.data[i]['type']};
                if(data.data[i]['type'] == 'image') {
                    imgslist.images.push(newobj);
                } else {
//                    if(data.data[i]['type'] == 'video') {
//                        newobj.path = '{:C("QINIU_RESOURCE_HOST")}' + data.data[i]['filepath'] + data.data[i]['filename'] + '?vframe/jpg/offset/10/w/' + data.data[i]['oriwidth'] + '/h/' + data.data[i]['oriheight'];
//                    }
                    videolist.images.push(newobj);
                }

            }
        }

    })



    var uploader = '';
    function uploadVideo() {
        var $list = $("#thelist");
            $btn = $('#ctlBtn'),
            state = 'pending';
        // 上传视频音频
        uploader = WebUploader.create({

            // 选完文件后，是否自动上传。
            auto: false,

            // swf文件路径
            swf: '__PUBLIC__/webUploader/Uploader.swf',

            // 文件接收服务端。
            server: 'http://up-z0.qiniu.com',

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#picker',

            duplicate: true,

            // 只允许选择图片文件。
            accept: {
                title: 'Video',
                extensions: 'mp3,mp4,flv,wmv,avi,mpg,mpeg,wma,wav',
                mimeTypes: 'video/*,audio/*,application/*'
            },
            formData: {
                token: "{$uploadToken}"
            }
        });

        var n = 1;
        uploader.on('uploadBeforeSend', function (block, data) {
            data['x:articleId'] ="{$Think.get.id}";
            if(/audio/.test(data.type)) {
                data['x:type'] = 'audio';
            } else if(/video/.test(data.type)) {
                data['x:type'] = 'video';
            }

//            if($.inArray(data.type, ['audio/mpeg', 'audio/wav', 'audio/ogg'])) {
//                data['x:type'] = 'audio';
//            } else if($.inArray(data.type, ['video/x-flv', 'video/mp4'])) {
//                data['x:type'] = 'video';
//            }
            data['x:sortDesc'] = n;

            console.log(data);
            n++;
        });


        // 当有文件添加进来的时候
        uploader.on("fileQueued", function(file) {
            console.log("fileQueued:");
            $('#thelist').css('display', 'table');
            $list.append( '<div id="' + file.id + '" class="item">' +
                    '<p class="info">' + file.name + '</p>' +
                    '<p class="progress-box"></p>' +
                    '<p class="webuploadDelbtn">删除</p>' +
                    '<p class="state">等待上传...</p>' +

                    '</div>' );

        });

        $(document).on('click', '.webuploadDelbtn', function () {
            var obj = $(this).parent();
            var info = uploader.getStats();
            console.log(info);
            uploader.removeFile(obj.attr('id'), true);
            obj.remove();
            if(info.queueNum == 1) {
                $('#thelist').html('');
                $('#thelist').css('display', 'none');
                uploader.reset();
            }
        });


        // 当某个文件上传到服务端响应后，会派送此事件来询问服务端响应是否有效。
//        uploader.on("uploadAccept", function(object, ret) {
//            // 服务器响应了
//            var data = JSON.parse(ret._raw);
//            if (data.resultCode != 0) {
//                uploader.reset();
//                alert("上传文件出现异常，请刷新后重新尝试。");
//                return false;
//            }
//        });

        //进度条事件
        uploader.on('uploadProgress', function (file, percentage) {
            var $li = $( '#'+file.id ),
                    $percent = $li.find('.progress .progress-bar'),
                    $progress = $li.find('.progress-box');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<div class="progress progress-striped active">' +
                        '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                        '</div>' +
                        '</div>').appendTo( $progress ).find('.progress-bar');
            }

            $li.find('p.state').text('上传中');
            $percent.css( 'width', percentage * 100 + '%' );
            $percent.css('text-align', 'center');
            $percent.css('color', '#fff');
            $percent.html(percentage * 100 + '%');

        });

        // 当文件上传成功时触发。
        uploader.on("uploadSuccess", function(file, response) {
            console.log(response);
           if(response.resultCode == 0) {
               n = 1;
               $("#" + file.id).find("p.state").text("已上传成功");
               $("#" + file.id).find('.webuploadDelbtn').remove();

               var newObj = {fullpath: response.fullpath,id:response.attachid,'path':response.path,'type':response.type};
               videolist.images.push(newObj);
               videolist.show =true;
               imgslist.show = false;
           } else {
               $("#" + file.id).find("p.state").text("未上传成功");
           }

        });

        uploader.on( 'uploadError', function( file ) {
            $( '#'+file.id ).find('p.state').text('上传出错');
        });

        uploader.on( 'uploadComplete', function( file ) {
            //$( '#'+file.id ).find('.progress').fadeOut();
        });

        uploader.on( 'all', function( type ) {
            if ( type === 'startUpload' ) {
                state = 'uploading';
            } else if ( type === 'stopUpload' ) {
                state = 'paused';
            } else if ( type === 'uploadFinished' ) {
                state = 'done';
            }

            if ( state === 'uploading' ) {
                $btn.text('暂停上传');
            } else {
                $btn.text('开始上传');
            }
        });

        $btn.on( 'click', function() {
            console.log("click:"+state);
            if ( state === 'uploading' ) {
                uploader.stop();
            } else {
                uploader.upload();
            }
        });

        // 所有文件上传成功后调用
        uploader.on('uploadFinished', function () {
            // 清空队列
            uploader.reset();
        });
    }

    $('#uploadVideo').on('hide.bs.modal', function () {
        $('#thelist').html('');
        $('#thelist').css('display', 'none');
        uploader.reset();
        if (uploader != "") {
            //用于防止每次调用 选择文件框变大 每次调用initUploader（）函数前，一定要将uploader销毁，要不然调用一次，上传文件框就会变大一次
            // uploader.destroy();
        }
    });
    isOpen = false;
    $('#uploadVideo').on('shown.bs.modal', function () {
        if(!isOpen){
            uploadVideo();
            isOpen = true;
        }
    });

//    $('.btn-primary').click(function () {
//        $('#articleForm').submit();
//    })


    /*    $(".cke_contents iframe").on("load", function(event){

     });*/
</script>
</body>
</html>